/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import gridFooter from './production_extend/Production_WorkOrderChildrenGridFooter'
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter,
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)
      this.boxOptions.height = document.documentElement.clientHeight * 0.5
      this.boxOptions.labelWidth = 120
      this.labelWidth = 120
      this.columnIndex = true
      let { permission } = this.$store.getters.getPermission(
        '/Production_WorkOrderList'
      )
      this.columns.splice(4, 0, {
        title: '状态',
        field: 'Status',
        width: 150,
        render(h, { row }) {
          return (
            <el-tag
              type={row.Status == 1 ? 'info' : row.Status == 2 ? '' : 'success'}
            >
              {row.Status == 1
                ? '未开始'
                : row.Status == 2
                ? '进行中'
                : '已完成'}
            </el-tag>
          )
        },
      })

      this.columns.unshift({
        title: '操作',
        field: 'action',
        width: 200,
        render: (h, { row }) => {
          let dom1 = ''
          let dom2 = ''
          if (permission.includes('createOutingPurchase')) {
            if (row.ProcessName.indexOf('委外') !== -1 && row.Status == '2') {
              dom1 = (
                <el-link
                  underline={false}
                  type="primary"
                  onClick={() => {
                    let formRules = [
                      [
                        {
                          title: '工单编号',
                          field: 'WorkOrderCode',
                          readonly: true,
                        },
                        {
                          title: '订单号',
                          field: 'MoCode',
                          readonly: true,
                        },
                      ],
                      [
                        {
                          title: '工序名称',
                          field: 'ProcessName',
                          readonly: true,
                        },
                        {
                          title: '工序编码',
                          field: 'ProcessCode',
                          readonly: true,
                        },
                      ],
                      [
                        {
                          title: '供应商',
                          field: 'Supplier',
                          type: 'select',
                          dataKey: 'Supplier',
                          required: true,
                        },
                        {
                          title: '数量',
                          field: 'Qty',
                          type: 'number',
                          min: 0,
                          required: true,
                        },
                      ],
                      [
                        {
                          title: '交货日期',
                          field: 'DeliveryDate',
                          type: 'datetime',
                          required: true,
                        },
                      ],
                    ]
                    this.$refs.gridFooter.open(row, '任务单', formRules)
                  }}
                >
                  <i class="el-icon-document"></i>
                  生成委外采购单
                </el-link>
              )
            }
          }

          if (permission.includes('print')) {
            dom2 = (
              <el-link
                style="margin-left: 5px;"
                underline={false}
                type="primary"
                onClick={async () => {
                  // console.log(row);
                  const res = await this.http.get(
                    `/api/Production_WorkOrder/GetInventoryNeedByWorkOrderListId?WorkOrderList_Id=${row.WorkOrderList_Id}`
                  )

                  this.print(row, res)
                }}
              >
                <i class="el-icon-printer"></i>
                打印
              </el-link>
            )
          }

          return h('div', null, [dom1, dom2])
        },
      })

      // this.buttons[1].hidden = true
      // this.buttons[2].hidden = true
      // this.buttons.splice(1, 0, {
      //   name: '开始',
      //   icon: 'el-icon-video-play',
      //   type: 'warning',
      //   onClick: async () => {
      //     let selected = this.$refs.table.getSelected()
      //     if (selected.length == 0) {
      //       this.$Message.error('请选择一条数据')
      //       return
      //     }

      //     try {
      //       let params = selected.map((item) => {
      //         if (item.Status !== '1') {
      //           throw new Error('选择的数据中有开过工的工单，请确认')
      //         }
      //         return {
      //           WorkOrderList_Id: item.WorkOrderList_Id,
      //           CurrentWoCode: item.CurrentWoCode,
      //         }
      //       })

      //       let res = await this.http.post(
      //         `api/Production_WorkOrderList/StartWork`,
      //         { list: params },
      //         true
      //       )
      //       if (res.message === null || res.message === '') {
      //         this.$message.success('创建成功')
      //       } else {
      //         this.$message.error(res.message)
      //       }
      //       this.search()
      //     } catch (err) {
      //       this.$message.error(err.message)
      //     }
      //   },
      // })
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
    },
    print(data, materialDetail) {
      console.log(data)
      console.log(materialDetail)
      let {
        MoCode,
        CurrentWoCode,
        ProcessName,
        PlanStartDate,
        PlanEndDate,
        PlanQty,
        ProductCode,
        ProductName,
      } = data
      let printWindow = window.open('', '_blank')
      printWindow.document.open()
      let style = `<style>
                      * {
                        margin: 0;
                        padding: 0;
                      }
                      .title {
                        text-align:center;
                        position: relative;
                      }

                      .header {
                        display: flex;
                        margin-bottom: 20px;
                        font-size: 14px;
                      }

                      .t_head {
                        flex: 1;
                      }

                      .t_head .th_item {
                        display: flex; 
                        list-style: none;
                      }

                      .t_head .th_item .th_title {
                        flex: 1; 
                        display: flex;
                        text-align: left;
                        text-indent: 20;
                      }

                      .th_title .th_title_space {
                        display: inline-block; 
                      }

                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                        font-size: 12px;
                      }

                      th {
                        border: 1px solid black;
                        height: 30px;
                      }

                      .grid_table tr td {
                        border: 1px solid black;
                        height: 30px;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: 
                        space-between; 
                        list-style: none;
                        font-size: 12px;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 150px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }
                    </style>`

      let title = `<div>
                        <h2 class="title">昆山鸿永峻精密五金电子科技有限公司</h2>
                        <h3 class="title">生产指令单</h3>
                    </div>`

      let header = `<div class="header">
                        <div class="t_head">
                          <ul class="th_item">
                            <li class="th_title">
                              订单号:
                              <span class="th_title_space" style="margin-left: 5px;">${
                                MoCode || ''
                              }</span>
                            </li>
                            <li class="th_title">
                              工单号:
                              <span class="th_title_space" style="margin-left: 5px;">${
                                CurrentWoCode || ''
                              }</span>
                            </li>
                          </ul>

                          <ul class="th_item">
                            <li class="th_title">
                                工序名称:
                                <span class="th_title_space" style="margin-left: 5px;">${
                                  ProcessName || ''
                                }</span>
                              </li>
                              <li class="th_title">
                                产品名称:
                                <span class="th_title_space" style="margin-left: 5px;">${
                                  ProductName || ''
                                }</span>
                            </li>
                          </ul>

                          <ul class="th_item">
                            <li class="th_title">
                            产品编码:
                            <span class="th_title_space" style="margin-left: 5px;">${
                              ProductCode || ''
                            }</span>
                          </li>
                          <li class="th_title">
                            计划数量:
                            <span class="th_title_space" style="margin-left: 5px;">${
                              PlanQty || ''
                            }</span>
                          </li>
                          </ul>
                          
                          <ul class="th_item">
                            <li class="th_title">
                              计划开始时间:
                              <span class="th_title_space" style="margin-left: 5px;">${
                                PlanStartDate || ''
                              }</span>
                            </li>
                            <li class="th_title">
                              计划结束时间:
                              <span class="th_title_space" style="margin-left: 5px;">${
                                PlanEndDate || ''
                              }</span>
                            </li>
                          </ul>
                        </div>
                    </div>`

      let footer = `<div>
                    <ul class="footer">
                    </ul>
                  <div>`
      let main = ''
      let detail = ''
      for (let i = 0; i < 9; i++) {
        main += `<tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>`
      }

      for (let i = 0; i < materialDetail.length; i++) {
        detail += `
      <tr>
        <td>${i + 1}</td>
        <td>${materialDetail[i].moCode || ''}</td>
        <td>${materialDetail[i].woCode || ''}</td>
        <td>${materialDetail[i].invCode || ''}</td>
        <td>${materialDetail[i].invName || ''}</td>
        <td>${materialDetail[i].invStd || ''}</td>
        <td>${materialDetail[i].unit || ''}</td>
        <td>${materialDetail[i].parentInvCode || ''}</td>
        <td>${materialDetail[i].iType || ''}</td>
        <td>${materialDetail[i].qty || ''}</td>
      </tr>`
      }

      let detailTable = `
      <table class="grid_table">
        <caption>物料需求</caption>
        <thead>
          <tr>
            <th>序号</th>
            <th>订单号</th>
            <th>工单号</th>
            <th>产品编码</th>
            <th>产品名称</th>
            <th>产品规格</th>
            <th>单位</th>
            <th>父级产品编码</th>
            <th>类别</th>
            <th>领料数量</th>
          </tr>
        </thead>
        <tbody>
          ${detail}
        </tbody>
      </table>
      `

      let body = `
      <table class="grid_table">
        <thead>
          <tr>
            <th colspan="8">产线生产记录</th>
          </tr>
          <tr>
            <th>序号</th>
            <th>机台</th>
            <th>良品数</th>
            <th>不良品数</th>
            <th>报废数</th>
            <th>开始时间</th>
            <th>结束时间</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          ${main}
        </tbody>
      </table>${footer}`

      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(title)
      printWindow.document.write(header)
      printWindow.document.write(materialDetail.length ? detailTable : '')
      printWindow.document.write(body)
      printWindow.document.write(`</body></html>`)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
